<script>
import HumanInfo from "@/views/aihuman/humanManagement/addHuman/humanInfo.vue";
import HumanFuZhuang from "@/views/aihuman/humanManagement/addHuman/humanFuZhuang.vue";
import HumanTimbre from "@/views/aihuman/humanManagement/addHuman/humanTimbre.vue";
import {uploadSound} from "@/api/aihuman/humanAssets/soundType";
import HumanModelStep from "@/views/aihuman/humanManagement/addHuman/humanModel.vue";
import {humanDetail, saveAimeta} from "@/api/aihuman/humanConfig/config";
import {uploadFile} from "@/api/aihuman/common/minio";
import {getUrl} from "@/util/aihuman/getUrl";

export default {
  name: "addHuman",
  components: {HumanModelStep, HumanTimbre, HumanFuZhuang, HumanInfo},
  data() {
    return {
      humanId: '',
      humanData: {},
      // 第一步 表单
      form: {
        aimetaName: '',
        aimetaUse: '',
        dimensionType: '',
        aimetaTag: '',
        status: 0,
        voiceImageLink: '',
        aimetaModel: '3',
        aimetaAvatar: ''
      },
      // 配置数据，收集动作、表情等数据
      configData: {},
      curStep: 1,
      steps: [
        {
          name: '基本信息',
          icon: require('@/assets/aihuman/humanManagement/humanstep1.png'),
          desc: '填写数字人基本信息',
          step: 1
        },
        {
          name: '动作与表情',
          icon: require('@/assets/aihuman/humanManagement/humanstep2.png'),
          desc: '设置数字人动作与表情 ',
          step: 2
        },
        {
          name: '服装',
          icon: require('@/assets/aihuman/humanManagement/humanstep3.png'),
          desc: '设置数字人的服装  ',
          step: 3
        },
        {
          name: '音色  ',
          icon: require('@/assets/aihuman/humanManagement/humanstep4.png'),
          desc: '设置数字人的音色  ',
          step: 4
        }
      ],
      loading: false
    }
  },
  created() {
  },
  methods: {
    getUrl,
    // 新增初始化数据
    initPage(activeName) {
      this.form.voiceImageLink = ''
      // 第一步数据
      this.$refs.humanInfo.form.aimetaName = ''
      this.$refs.humanInfo.form.dimensionType = activeName
      this.$refs.humanInfo.form.aimetaUse = '2'
      this.$refs.humanInfo.form.status = 0
      this.$refs.humanInfo.form.aimetaTag = ''
      this.$refs.humanInfo.form.aimetaAvatar = ''
      this.$refs.humanInfo.dynamicTags = []
      this.$nextTick(() => {
        this.$refs.humanInfo.$refs.form.clearValidate()
      })
      // 第二步数据
      this.$refs.humanModelStep.model = []
      this.$refs.humanModelStep.attitudes = []
      this.$refs.humanModelStep.expressions = []
      this.$refs.humanModelStep.actions = []

      // 第三部 数据
      this.$refs.fuzhuang.fuzhuang = []
      this.$refs.fuzhuang.defaultDress = []

      //   第四部数据
      this.$refs.soundRef.sound = []
    },
    /**
     * 数字人详情
     * @param id
     * @returns {Promise<void>}
     */
    async getDetail(id) {
      this.loading = true
      const {data} = await humanDetail(id)
      this.form.voiceImageLink = data.data.voiceImageLink
      // 第一步数据
      this.$refs.humanInfo.form.aimetaName = data.data.aimetaName
      this.$refs.humanInfo.form.dimensionType = data.data.dimensionType.toString()
      this.$refs.humanInfo.form.aimetaUse = data.data.aimetaUse
      this.$refs.humanInfo.form.status = data.data.status
      this.$refs.humanInfo.form.aimetaTag = data.data.aimetaTag
      this.$refs.humanInfo.form.aimetaAvatar = data.data.aimetaAvatar
      this.$refs.humanInfo.dynamicTags = data.data.aimetaTag ? data.data.aimetaTag.split(',') : []
      this.$refs.humanInfo.$refs.form.clearValidate()
      // 第二步数据
      if (data.data.aimetaAssetsModel) {
        this.$refs.humanModelStep.model = [data.data.aimetaAssetsModel]
      } else {
        this.$refs.humanModelStep.model = []
      }

      if (data.data.aimetaAssetsModel && data.data.aimetaAssetsModel.attitudes) {
        let result = JSON.parse(data.data.aimetaAssetsModel.attitudes)
        let temp = result.find(item => item.value === data.data.defaultAttitudeId)
        this.$refs.humanModelStep.attitudes = temp ? [temp] : []
      } else {
        this.$refs.humanModelStep.attitudes = []
      }


      if (data.data.aimetaAssetsModel && data.data.aimetaAssetsModel.expressions) {
        let arr = JSON.parse(data.data.aimetaAssetsModel.expressions)
        let arrItem = arr.find(item => item.value === data.data.defaultExpressionId)
        this.$refs.humanModelStep.expressions = arrItem ? [arrItem] : []
      } else {
        this.$refs.humanModelStep.expressions = []
      }
      this.$refs.humanModelStep.actions = [data.data.actionPackageInfo.actionPackage] || []

      // 第三部 数据
      this.$refs.fuzhuang.fuzhuang = data.data.costumesPackageInfo.map(el=> el.costumePackage)
      this.$refs.fuzhuang.defaultDress = [data.data.defaultAimetaAssetsCharacterCostumes] || []

      //   第四部数据
      this.$refs.soundRef.sound = data.data.defaultAimetaAssetsSoundType ? [data.data.defaultAimetaAssetsSoundType] : []

      this.loading = false
    },
    async uploadHumanImg(file) {
      let formData = new FormData()
      formData.append('file', file.file)
      formData.append('keyFolderPath', 'humanManagement/humanConfig')

      const {data} = await uploadFile(formData)
      this.form.voiceImageLink = data.data.filePath
    },
    handleCancel() {
      this.$emit('on-cancel')
    },
    handlePrev() {
      if (this.curStep === 1) {
        return false
      }
      this.curStep--
    },
    async saveData() {
      this.configData.sound = this.$refs.soundRef.sound

      // 去掉数字人选择
      // if (this.form.voiceImageLink === '') {
      //   this.$message.error('请上传数字人形象图')
      //   return
      // }

      if (this.configData.sound && this.configData.sound.length === 0) {
        this.$message.error('音色不能为空')
        return
      }

      if (this.configData.dress.length === 0) {
        this.$message.error('服饰不能为空')
        return
      }

      if (this.configData.defaultDress.length === 0) {
        this.$message.error('默认服饰不能为空')
        return
      }

      if (this.configData.actions.length === 0) {
        this.$message.error('动作不能为空')
        return
      }

      let costumesPackageId = this.configData.dress.map(item=> item.id)
      console.log(costumesPackageId);
      const params = {
        ...this.form,
        id: this.humanId,
        defaultAttitudeId: this.configData.attitudes.length > 0 ? this.configData.attitudes[0].value : '',
        defaultExpressionId: this.configData.expressions.length > 0 ? this.configData.expressions[0].value : '',
        defaultCostumeId: this.configData.defaultDress.length > 0 ? this.configData.defaultDress[0].id : '',
        defaultSoundId: this.configData.sound.length > 0 ? this.configData.sound[0].id : '',
        aimetaAssetsModelId: this.configData.model.length > 0 ? this.configData.model[0].id : '',
        actionPackageId: this.configData.actions.length > 0 ? this.configData.actions[0].id : '',
        costumesList: this.configData.dress,
        costumesPackageId: costumesPackageId.join(',')
      }
      console.log(params);
      const {data} = await saveAimeta(params)
      this.$message.success(data.msg)
      this.$emit('ok')
    },
    handleNext() {
      if (this.curStep === 4) return false
      if (this.curStep === 1) {
        this.$refs.humanInfo.$refs['form'].validate((valid) => {
          if (valid) {
            let data = this.$refs.humanInfo.form
            this.form = {...this.form, ...data}
            this.$refs.humanModelStep.$refs.humanModelDialog.costumesType = this.form.dimensionType
            this.$refs.humanModelStep.$refs.humanAction.costumesType = this.form.dimensionType
            this.$refs.fuzhuang.$refs.dialog.costumesType = this.form.dimensionType

            if (this.form.voiceImageLink === '') {
              this.$message.error('请上传数字人形象图')
              return
            }

            this.curStep++
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      } else if (this.curStep === 2) {
        console.log(this.configData, '点击第二部的下一步按钮');
        // 去掉数字人选择
        // if (this.$refs.humanModelStep.model.length === 0) {
        //   this.$message.error('数字人模型不能为空')
        //   return false
        // }

        if (this.$refs.humanModelStep.actions.length === 0) {
          this.$message.error('动作不能为空')
          return
        }

        this.configData.model = this.$refs.humanModelStep.model
        this.configData.actions = this.$refs.humanModelStep.actions
        this.configData.attitudes = this.$refs.humanModelStep.attitudes
        this.configData.expressions = this.$refs.humanModelStep.expressions
        this.curStep++
      } else if (this.curStep === 3) {
        if (this.$refs.fuzhuang.fuzhuang.length === 0) {
          this.$message.error('服饰不能为空')
          return
        }

        if (this.$refs.fuzhuang.defaultDress.length === 0) {
          this.$message.error('默认服饰不能为空')
          return
        }

        this.configData.dress = this.$refs.fuzhuang.fuzhuang
        this.configData.defaultDress = this.$refs.fuzhuang.defaultDress
        this.curStep++
      } else {
        if (this.$refs.soundRef.sound.length === 0 ){
          this.$message.error('默认音色不能为空')
          return
        }

        this.configData.sound = this.$refs.soundRef.sound
      }
    }
  }
}
</script>

<template>
  <div>
    <header class="human-header">
      <div
        v-for="(item, index) in steps"
        :key="index"
        :class="['step-box', {active: curStep === item.step}]">
        <img :src="item.icon" alt="">
        <div class="step-title">
          {{ item.name }}
        </div>
        <div class="step-desc">
          {{ item.desc }}
        </div>
      </div>
    </header>

    <div class="content" v-loading="loading">
      <div class="human-upload">
        <el-upload
          class="human-uploader"
          :http-request="uploadHumanImg"
          action=""
          accept="image/*"
          :show-file-list="false">
          <img v-if="form.voiceImageLink" :src="getUrl() + form.voiceImageLink" class="human-img"/>
          <template v-else>
            <i class="el-icon-upload2"></i>
            <div>上传数字人形象</div>
          </template>
        </el-upload>
      </div>
      <div class="content-main">
        <human-info
          ref="humanInfo"
          v-show="curStep === 1"
        />

        <human-model-step
          ref="humanModelStep"
          v-show="curStep === 2"
        />
        <human-fu-zhuang
          ref="fuzhuang"
          v-show="curStep === 3"
        />

        <human-timbre
          ref="soundRef"
          v-show="curStep === 4"
        />
      </div>

    </div>

    <div class="button-box">
      <el-button @click="handleCancel">取消</el-button>
      <el-button v-if="curStep > 1" type="primary" @click="handlePrev">上一步</el-button>
      <el-button v-if="curStep === 4" type="primary" @click="saveData">保存</el-button>
      <el-button v-else type="primary" @click="handleNext">下一步</el-button>
    </div>
  </div>
</template>

<style scoped lang="scss">
.button-box {
  border-top: 1px solid #E4E7ED;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding-top: 15px;
  margin-top: 15px;
}

.content-main {
  flex: 1;
}

.human-img {
  height: 100%;
  width: 100%;
  object-fit: contain;
}

.human-uploader {
  background: #F5F8FF;
  height: 450px;
  width: 400px;

  /deep/ .el-upload {
    height: 100%;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;

    i {
      font-size: 40px;
      color: #999;
    }
  }
}

.human-upload {
  margin-right: 20px;
}

.content {
  padding-top: 15px;
  display: flex;
}

.step-desc {
  font-size: 14px;
  padding-top: 8px;
}

.step-title {
  font-weight: bold;
  font-size: 18px;
}

.step-box {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  position: relative;

  &.active {
    &::after {
      background: #0B57D6;
      position: absolute;
      content: '';
      height: 2px;
      width: 100%;
      top: 120px;
      left: 50%;
      transform: translateX(-50%);
    }
  }
}

.human-header {
  border-bottom: #EEEFF2 2px solid;
  height: 120px;
  display: flex;
  justify-content: space-between;
}
</style>
